package com.redijedi.tapestry5.internal;

import com.redijedi.tapestry5.TreeNodeModel;

/**
 * 
 * @author torr
 * 
 */
public enum TreeLoopAction {

	CONTINUE, OPEN_TREE, OPEN_PARENT_NODE, OPEN_NODE, CLOSE_NODE, CLOSE_PARENT_NODE, CLOSE_TREE;

	public static TreeLoopAction valueOf(TreeLoopState state,
			TreeNodeModel prev, TreeNodeModel curr, TreeNodeModel next) {
		int prevDepth = (prev == null ? -1 : prev.getDepth());
		int currDepth = (curr == null ? -2 : curr.getDepth());
		int nextDepth = (next == null ? -2 : next.getDepth());

		switch (state) {
		case OPENING:
			if (prevDepth == -1) {
				return OPEN_TREE;
			}
			if (nextDepth != -2) {
				if (currDepth > nextDepth) {
					return OPEN_NODE;
				}
			}
			if (nextDepth == currDepth) {
				return OPEN_NODE;
			}
			if (nextDepth > currDepth) {
				return OPEN_PARENT_NODE;
			}
			break;
		case CLOSING:
			if (currDepth == -2) {
				return CLOSE_TREE;
			}
			if (nextDepth != -2) {
				if (currDepth > nextDepth) {
					return CLOSE_NODE;
				}
			}
			if (nextDepth == currDepth) {
				return CLOSE_NODE;
			}
			if (nextDepth < currDepth) {
				return CLOSE_PARENT_NODE;
			}
		}

		return CONTINUE;
	}
}